/** axios封装
 * 请求拦截、相应拦截、错误统一处理
 */
import Vue from 'vue'
import axios from 'axios'
import QS from 'qs'
import router from '../router'

/* 设置默认请求路径 */
axios.defaults.baseURL = process.env.VUE_APP_BASE_API

// 请求超时时间
axios.defaults.timeout = 10000

// post请求头
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'

// 请求拦截器
axios.interceptors.request.use(
  config => {
    const token = Vue.$cookies.get('token')
    if (token) {
      config.headers.token = token
    }
    return config
  },
  error => {
    return Promise.error(error)
  })

// 响应拦截器
axios.interceptors.response.use(
  response => {
    if (response.status === 200) {
      if (response.data.code === 401) {
        Vue.prototype.$alert('请登录！', { type: 'error' }).then(() => {
          router.replace('/login')
        })
      } else {
        return Promise.resolve(response)
      }
    } else {
      return Promise.reject(response)
    }
  },
  // 服务器状态码不是200的情况
  error => {
    return Promise.reject(error.response)
  }
)

const http = {
  get (url, params) {
    return new Promise((resolve, reject) => {
      axios.get(url, {
        params: params
      })
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject(err.data)
        })
    })
  },
  post (url, params, isQs = false) {
    return new Promise((resolve, reject) => {
      axios.post(url, isQs ? QS.stringify(params) : params)
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject(err.data)
        })
    })
  },
  delete (url, params) {
    return new Promise((resolve, reject) => {
      axios.delete(url, { params }).then(res => {
        resolve(res.data)
      }).catch(err => {
        reject(err.data)
      })
    })
  }
}
Vue.prototype.$http = http
